package cn.stylefeng.guns.modular.order.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;

import cn.stylefeng.guns.modular.basic.entity.BasicCustomer;
import cn.stylefeng.guns.modular.basic.model.params.BasicGoodsParam;
import cn.stylefeng.guns.modular.basic.model.result.BasicGoodsResult;
import cn.stylefeng.guns.modular.basic.service.BasicGoodsService;
import cn.stylefeng.guns.modular.order.entity.WhOutOrder;
import cn.stylefeng.guns.modular.order.mapper.WhOutOrderMapper;
import cn.stylefeng.guns.modular.order.model.params.OutOrderDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.OutOrderParam;
import cn.stylefeng.guns.modular.order.model.params.WhOutOrderDetailedParam;
import cn.stylefeng.guns.modular.order.model.params.WhOutOrderParam;
import cn.stylefeng.guns.modular.order.model.result.OutOrderResult;
import cn.stylefeng.guns.modular.order.model.result.WhOutOrderResult;
import cn.stylefeng.guns.modular.order.service.WhOutOrderDetailedService;
import cn.stylefeng.guns.modular.order.service.WhOutOrderService;
import cn.stylefeng.guns.modular.replenishment.service.ReplenishmentOrderService;
import cn.stylefeng.guns.modular.rest.storage.ExpressDeliveryGoods;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.beetl.core.parser.BeetlParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 武汉出库订单表 服务实现类
 * </p>
 *
 * @author wp
 * @since 2025-09-30
 */
@Service
public class WhOutOrderServiceImpl extends ServiceImpl<WhOutOrderMapper, WhOutOrder> implements WhOutOrderService {


    @Autowired
    private BasicGoodsService goodsService;
    @Autowired
    private WhOutOrderDetailedService whOutOrderDetailedService;

    @Autowired
    private ReplenishmentOrderService replenishmentOrderService;
    @Override
    public void add(WhOutOrderParam param){
        WhOutOrder entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(WhOutOrderParam param){
        this.removeById(getKey(param));
    }

    @Override
    public void update(WhOutOrderParam param){
        WhOutOrder oldEntity = getOldEntity(param);
        WhOutOrder newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public WhOutOrderResult findBySpec(WhOutOrderParam param){
        return null;
    }

    @Override
    public List<WhOutOrderResult> findListBySpec(WhOutOrderParam param){
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(WhOutOrderParam param,String condition){
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param,condition);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseData saveJstOutOrder(JSONObject data, User user, BasicCustomer byId) {
//		String body = jstDdcx.getBody();
//		OutOrderParam param = new OutOrderParam();
//		outOrderService.add(param);
//		Object data = new JSONObject(jstDdcx.getBody()).get("data");
        Long[] ids = new Long[]{};
        Object datas = new JSONObject(data).get("datas");


        JSONArray jsonArray = new JSONArray(datas);
        for (int i = 0; i < jsonArray.size(); i++) {

            WhOutOrderParam outOrderParam= new  WhOutOrderParam();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            Object batchs = jsonObject.get("batchs");
            Object l_id = jsonObject.get("l_id");


            JSONArray batchsJsonArray = new JSONArray(batchs);
            Object items = jsonObject.get("items");
            JSONArray itemsJsonArray = new JSONArray(items);
            // 订单编号
            Object io_id = jsonObject.get("io_id");
            Object o_id = jsonObject.get("o_id");


            //修改时间
            Object modified = jsonObject.get("modified");

            outOrderParam.setDeptId(user.getDeptId());
            outOrderParam.setDeliverId(user.getDeliverId());
            /**
             * 出库订单
             */
            //客户单号
            outOrderParam.setOutCustomerId(147l);
            //客户名称
            outOrderParam.setOutCustomerName(byId.getCustomerName());
            //仓库
            outOrderParam.setOutStorehouseId(122l);
            //仓库名称
            outOrderParam.setStorehouseName("海氏海诺武汉仓");
            //出库单号
            outOrderParam.setOutOrderNumber(io_id.toString());
            //快递单号
            outOrderParam.setExpressDelivery(l_id.toString());
            outOrderParam.setOutWay("配送");
            outOrderParam.setTransportWay("汽运");
            outOrderParam.setSetMentiontime(data.getStr("io_date"));
            outOrderParam.setCustomerNumber(o_id.toString());
//            if("大坝来货出库专用".equals(jsonObject.get("shop_name"))){
//                continue;
//            }else if("大坝向黄河北下单专用".equals(jsonObject.get("shop_name"))){
//                outOrderParam.setCustomerNumber(o_id.toString()+"大坝");
//                outOrderParam.setGetUnit("大坝");
//                outOrderParam.setGetUnitId(31683L);
//                outOrderParam.setGetLocationId(32069L);
//                outOrderParam.setGetLocation("宇佳智慧物流大坝");
//            }else if("大单".equals(jsonObject.get("shop_name"))){
//                outOrderParam.setCustomerNumber(o_id.toString() +"大单");
//                outOrderParam.setGetUnit("大单");
//                outOrderParam.setGetUnitId(31684L);
//
//                outOrderParam.setGetLocationId(32068L);
//                outOrderParam.setGetLocation("宇佳智慧物流大单");
//            }else if("门店预包".equals(jsonObject.get("shop_name"))){
//                outOrderParam.setCustomerNumber(o_id.toString() +"预包");
//                outOrderParam.setGetUnit("预包");
//                outOrderParam.setGetUnitId(32737L);
//
//                outOrderParam.setGetLocationId(33127L);
//                outOrderParam.setGetLocation("宇佳智慧物流大单");
//            }else { //小货架向大货架下单
//                outOrderParam.setCustomerNumber(o_id.toString());
//                outOrderParam.setGetUnit("小货架");
//                outOrderParam.setGetUnitId(31685L);
//                outOrderParam.setGetLocationId(32067L);
//                outOrderParam.setGetLocation("宇佳智慧物流小货架");
//            }
//			outOrderParam.setGetUnit(jsonObject.get("shop_name").toString());

//			Object buyer_message = jsonObject.get("buyer_message");
//            Object buyer_message = jsonObject.get("remark");
//            String buyer_messageStr = "";
//            if(buyer_message != null){
//                buyer_messageStr = buyer_message.toString();
//                if(buyer_messageStr.contains("补单")){
//                    outOrderParam.setCustomerNumber(o_id.toString()+"补单");
//                    outOrderParam.setGetUnit("补单");
//                    outOrderParam.setGetUnitId(31689L);
//                    outOrderParam.setGetLocationId(32073L);
//                    outOrderParam.setGetLocation("宇佳智慧物流补单");
//                }
//            }


            outOrderParam.setOutOrderStatus("PENDING_SUBMIT");
            System.out.println(outOrderParam);
            outOrderParam.setSetMentiontime(cn.stylefeng.guns.core.util.DateUtil.getDate());
            outOrderParam.setCreateTime(new Date());
//			OutOrderResult outOrderResult = outOrderService.findbyoutOrderNumber(io_id.toString());
            WhOutOrderResult outOrderResult = findbyoutOrderNumberByDeptId(o_id.toString(),io_id.toString(),user.getDeptId());
            if(outOrderResult != null){
                continue;
            }
//			outOrderService.add(outOrderParam);
            add(outOrderParam);


            /**
             * 出库订单详细
             */
            List<WhOutOrderDetailedParam> list = new ArrayList<>();
            itemsJsonArray.forEach(item -> {
                JSONObject jsonObject2 = new JSONObject(item);
                WhOutOrderDetailedParam outOrderDetailedParam = new WhOutOrderDetailedParam();
                outOrderDetailedParam.setDetailedOutNumber(io_id.toString());
                outOrderDetailedParam.setDetailedNumber(jsonObject2.getStr("qty"));
                outOrderDetailedParam.setDetailedGoodsname(jsonObject2.getStr("name"));
                outOrderDetailedParam.setGoodsUnit(jsonObject2.getStr("unit"));
                outOrderDetailedParam.setDetailedPrice(jsonObject2.getStr("sale_price"));
                outOrderDetailedParam.setDetailedMoney(jsonObject2.getStr("sale_amount"));	// 价格*数量
                outOrderDetailedParam.setCreateTime(new Date());
                outOrderDetailedParam.setDetailedGoodscode(jsonObject2.getStr("sku_id"));

                BasicGoodsParam basicGoodsParam = new BasicGoodsParam();
                basicGoodsParam.setGoodsNumber(jsonObject2.getStr("sku_id"));
                basicGoodsParam.setDeptId(user.getDeptId());
                BasicGoodsResult bySpec = goodsService.findBySpec(basicGoodsParam, user.getOperateId());
                outOrderDetailedParam.setDetailedGoodsId(Long.parseLong(bySpec.getId().toString()));
                batchsJsonArray.forEach(batch -> {
                    JSONObject jsonObject3 = new JSONObject(batch);
                    if (jsonObject3.getStr("sku_id").equals(jsonObject2.getStr("sku_id"))) {
                        if(ToolUtil.isNotEmpty(byId.getGoodsBatchFlag()) && "是".equals(byId.getGoodsBatchFlag())){
                            outOrderDetailedParam.setDetailedBatchnumber(jsonObject3.getStr("batch_no"));
                        }
                        outOrderDetailedParam.setDetailedDate(jsonObject3.getStr("product_date"));
                    }
                });

                list.add(outOrderDetailedParam);
                //补货
				replenishmentOrderService.generateWhReplenishmentOrder(jsonObject2.getStr("sku_id"), jsonObject2.getStr("qty"));
            });

            whOutOrderDetailedService.saveBatchList(list);
//            Integer id = outOrderParam.getId();
//            Long[] ids1 = {Long.parseLong(id.toString())};
//            jstOutOrderScheduledService.submitJSTOutOrder(ids1);
        }

        return ResponseData.success();
    }

    @Override
    public WhOutOrderResult findbyoutOrderNumberByDeptId(String  customerNumber,String  outOrderNumber,Long deptId) {
        return this.baseMapper.findbyoutOrderNumberByDeptId(customerNumber,outOrderNumber,deptId);
    }

    @Override
    public List<ExpressDeliveryGoods> findExpressDeliveryGoodsListBySpec(String[] expressDelivery, int outStorehouseId) {
        return this.baseMapper.findExpressDeliveryGoodsListBySpec(expressDelivery, outStorehouseId);
    }

    private Serializable getKey(WhOutOrderParam param){
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private WhOutOrder getOldEntity(WhOutOrderParam param) {
        return this.getById(getKey(param));
    }

    private WhOutOrder getEntity(WhOutOrderParam param) {
        WhOutOrder entity = new WhOutOrder();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

}
